{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Networks with Parallel Concatenations (GoogLeNet)\n",
    "\n",
    ":label:`sec_googlenet`\n",
    "\n",
    "\n",
    "In 2014, :cite:`Szegedy.Liu.Jia.ea.2015`\n",
    "won the ImageNet Challenge, proposing a structure\n",
    "that combined the strengths of the NiN and repeated blocks paradigms.\n",
    "One focus of the paper was to address the question\n",
    "of which sized convolutional kernels are best.\n",
    "After all, previous popular networks employed choices\n",
    "as small as $1 \\times 1$ and as large as $11 \\times 11$.\n",
    "One insight in this paper was that sometimes\n",
    "it can be advantageous to employ a combination of variously-sized kernels.\n",
    "In this section, we will introduce GoogLeNet,\n",
    "presenting a slightly simplified version of the original model---we\n",
    "omit a few ad hoc features that were added to stabilize training\n",
    "but are unnecessary now with better training algorithms available.\n",
    "\n",
    "## Inception Blocks\n",
    "\n",
    "The basic convolutional block in GoogLeNet is called an Inception block,\n",
    "likely named due to a quote from the movie Inception (\"We Need To Go Deeper\"),\n",
    "which launched a viral meme.\n",
    "\n",
    "![Structure of the Inception block. ](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/inception.svg)\n",
    "\n",
    "As depicted in the figure above,\n",
    "the inception block consists of four parallel paths.\n",
    "The first three paths use convolutional layers\n",
    "with window sizes of $1\\times 1$, $3\\times 3$, and $5\\times 5$\n",
    "to extract information from different spatial sizes.\n",
    "The middle two paths perform a $1\\times 1$ convolution on the input\n",
    "to reduce the number of input channels, reducing the model's complexity.\n",
    "The fourth path uses a $3\\times 3$ maximum pooling layer,\n",
    "followed by a $1\\times 1$ convolutional layer\n",
    "to change the number of channels.\n",
    "The four paths all use appropriate padding to give the input and output the same height and width.\n",
    "Finally, the outputs along each path are concatenated\n",
    "along the channel dimension and comprise the block's output.\n",
    "The commonly-tuned parameters of the Inception block\n",
    "are the number of output channels per layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/Accumulator.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.basicdataset.cv.classification.*;\n",
    "import org.apache.commons.lang3.ArrayUtils;\n",
    "import java.util.stream.*;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "1"
    }
   },
   "outputs": [],
   "source": [
    "// c1 - c4 are the number of output channels for each layer in the path\n",
    "public ParallelBlock inceptionBlock(int c1, int[] c2, int[] c3, int c4) {\n",
    "\n",
    "    // Path 1 is a single 1 x 1 convolutional layer\n",
    "    SequentialBlock p1 = new SequentialBlock().add(\n",
    "            Conv2d.builder()\n",
    "                    .setFilters(c1)\n",
    "                    .setKernelShape(new Shape(1, 1))\n",
    "                    .build())\n",
    "            .add(Activation::relu);\n",
    "\n",
    "    // Path 2 is a 1 x 1 convolutional layer followed by a 3 x 3\n",
    "    // convolutional layer\n",
    "    SequentialBlock p2 = new SequentialBlock().add(\n",
    "            Conv2d.builder()\n",
    "                    .setFilters(c2[0])\n",
    "                    .setKernelShape(new Shape(1, 1))\n",
    "                    .build())\n",
    "            .add(Activation::relu)\n",
    "            .add(\n",
    "                    Conv2d.builder()\n",
    "                            .setFilters(c2[1])\n",
    "                            .setKernelShape(new Shape(3, 3))\n",
    "                            .optPadding(new Shape(1, 1))\n",
    "                            .build())\n",
    "            .add(Activation::relu);\n",
    "\n",
    "    // Path 3 is a 1 x 1 convolutional layer followed by a 5 x 5\n",
    "    // convolutional layer\n",
    "    SequentialBlock p3 = new SequentialBlock().add(\n",
    "            Conv2d.builder()\n",
    "                    .setFilters(c3[0])\n",
    "                    .setKernelShape(new Shape(1, 1))\n",
    "                    .build())\n",
    "            .add(Activation::relu)\n",
    "            .add(\n",
    "                    Conv2d.builder()\n",
    "                            .setFilters(c3[1])\n",
    "                            .setKernelShape(new Shape(5, 5))\n",
    "                            .optPadding(new Shape(2, 2))\n",
    "                            .build())\n",
    "            .add(Activation::relu);\n",
    "\n",
    "    // Path 4 is a 3 x 3 maximum pooling layer followed by a 1 x 1\n",
    "    // convolutional layer\n",
    "    SequentialBlock p4 = new SequentialBlock()\n",
    "            .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(1, 1), new Shape(1, 1)))\n",
    "            .add(Conv2d.builder()\n",
    "                    .setFilters(c4)\n",
    "                    .setKernelShape(new Shape(1, 1))\n",
    "                    .build())\n",
    "            .add(Activation::relu);\n",
    "\n",
    "    // Concatenate the outputs on the channel dimension\n",
    "    return new ParallelBlock(\n",
    "                        list -> {\n",
    "                            List<NDArray> concatenatedList = list\n",
    "                                    .stream()\n",
    "                                    .map(NDList::head)\n",
    "                                    .collect(Collectors.toList());\n",
    "\n",
    "                            return new NDList(NDArrays.concat(new NDList(concatenatedList), 1));\n",
    "                        }, Arrays.asList(p1, p2, p3, p4));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To gain some intuition for why this network works so well,\n",
    "consider the combination of the filters.\n",
    "They explore the image in varying ranges.\n",
    "This means that details at different extents\n",
    "can be recognized efficiently by different filters.\n",
    "At the same time, we can allocate different amounts of parameters\n",
    "for different ranges (e.g., more for short range\n",
    "but not ignore the long range entirely).\n",
    "\n",
    "## GoogLeNet Model\n",
    "\n",
    "As shown in :numref:`fig_inception_full`, GoogLeNet uses a stack of a total of 9 inception blocks\n",
    "and global average pooling to generate its estimates.\n",
    "Maximum pooling between inception blocks reduced the dimensionality.\n",
    "The first part is identical to AlexNet and LeNet,\n",
    "the stack of blocks is inherited from VGG\n",
    "and the global average pooling avoids\n",
    "a stack of fully-connected layers at the end.\n",
    "The architecture is depicted below.\n",
    "\n",
    "![Full GoogLeNet Model](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/inception-full.svg)\n",
    "\n",
    ":label:`fig_inception_full`\n",
    "\n",
    "\n",
    "We can now implement GoogLeNet piece by piece.\n",
    "The first component uses a 64-channel $7\\times 7$ convolutional layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [],
   "source": [
    "SequentialBlock block1 = new SequentialBlock();\n",
    "block1\n",
    "    .add(Conv2d.builder()\n",
    "                .setKernelShape(new Shape(7, 7))\n",
    "                .optPadding(new Shape(3, 3))\n",
    "                .optStride(new Shape(2, 2))\n",
    "                .setFilters(64)\n",
    "                .build())\n",
    "    .add(Activation::relu)\n",
    "    .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2), new Shape(1, 1)));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second component uses two convolutional layers:\n",
    "first, a 64-channel $1\\times 1$ convolutional layer,\n",
    "then a $3\\times 3$ convolutional layer that triples the number of channels. This corresponds to the second path in the Inception block."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "3"
    }
   },
   "outputs": [],
   "source": [
    "SequentialBlock block2 = new SequentialBlock();\n",
    "block2\n",
    "    .add(Conv2d.builder()\n",
    "            .setFilters(64)\n",
    "            .setKernelShape(new Shape(1, 1))\n",
    "            .build())\n",
    "    .add(Activation::relu)\n",
    "    .add(Conv2d.builder()\n",
    "            .setFilters(192)\n",
    "            .setKernelShape(new Shape(3, 3))\n",
    "            .optPadding(new Shape(1, 1))\n",
    "            .build())\n",
    "    .add(Activation::relu)\n",
    "    .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2), new Shape(1, 1)));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The third component connects two complete Inception blocks in series.\n",
    "The number of output channels of the first Inception block is\n",
    "$64+128+32+32=256$, and the ratio to the output channels\n",
    "of the four paths is $64:128:32:32=2:4:1:1$.\n",
    "The second and third paths first reduce the number of input channels\n",
    "to $96/192=1/2$ and $16/192=1/12$, respectively,\n",
    "and then connect the second convolutional layer.\n",
    "The number of output channels of the second Inception block\n",
    "is increased to $128+192+96+64=480$, and the ratio to the number of output channels per path is $128:192:96:64 = 4:6:3:2$.\n",
    "The second and third paths first reduce the number of input channels\n",
    "to $128/256=1/2$ and $32/256=1/8$, respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "4"
    }
   },
   "outputs": [],
   "source": [
    "SequentialBlock block3 = new SequentialBlock();\n",
    "block3\n",
    "        .add(inceptionBlock(64, new int[]{96, 128}, new int[]{16, 32}, 32))\n",
    "        .add(inceptionBlock(128, new int[]{128, 192}, new int[]{32, 96}, 64))\n",
    "        .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2), new Shape(1, 1)));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fourth block is more complicated.\n",
    "It connects five Inception blocks in series,\n",
    "and they have $192+208+48+64=512$, $160+224+64+64=512$,\n",
    "$128+256+64+64=512$, $112+288+64+64=528$,\n",
    "and $256+320+128+128=832$ output channels, respectively.\n",
    "The number of channels assigned to these paths is similar\n",
    "to that in the third module:\n",
    "the second path with the $3\\times 3$ convolutional layer\n",
    "outputs the largest number of channels,\n",
    "followed by the first path with only the $1\\times 1$ convolutional layer,\n",
    "the third path with the $5\\times 5$ convolutional layer,\n",
    "and the fourth path with the $3\\times 3$ maximum pooling layer.\n",
    "The second and third paths will first reduce\n",
    "the number of channels according the ratio.\n",
    "These ratios are slightly different in different Inception blocks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "5"
    }
   },
   "outputs": [],
   "source": [
    "SequentialBlock block4 = new SequentialBlock();\n",
    "block4\n",
    "        .add(inceptionBlock(192, new int[]{96, 208}, new int[]{16, 48}, 64))\n",
    "        .add(inceptionBlock(160, new int[]{112, 224}, new int[]{24, 64}, 64))\n",
    "        .add(inceptionBlock(128, new int[]{128, 256}, new int[]{24, 64}, 64))\n",
    "        .add(inceptionBlock(112, new int[]{144, 288}, new int[]{32, 64}, 64))\n",
    "        .add(inceptionBlock(256, new int[]{160, 320}, new int[]{32, 128}, 128))\n",
    "        .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2), new Shape(1, 1)));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fifth block has two Inception blocks with $256+320+128+128=832$\n",
    "and $384+384+128+128=1024$ output channels.\n",
    "The number of channels assigned to each path\n",
    "is the same as that in the third and fourth modules,\n",
    "but differs in specific values.\n",
    "It should be noted that the fifth block is followed by the output layer.\n",
    "This block uses the global average pooling layer\n",
    "to change the height and width of each channel to 1, just as in NiN.\n",
    "Finally, we turn the output into a two-dimensional array\n",
    "followed by a fully-connected layer\n",
    "whose number of outputs is the number of label classes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "6"
    }
   },
   "outputs": [],
   "source": [
    "SequentialBlock block5 = new SequentialBlock();\n",
    "block5\n",
    "        .add(inceptionBlock(256, new int[]{160, 320}, new int[]{32, 128}, 128))\n",
    "        .add(inceptionBlock(384, new int[]{192, 384}, new int[]{48, 128}, 128))\n",
    "        .add(Pool.globalAvgPool2dBlock());\n",
    "\n",
    "SequentialBlock block = new SequentialBlock();\n",
    "block = block.addAll(block1, block2, block3, block4, block5, Linear.builder().setUnits(10).build());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The GoogLeNet model is computationally complex,\n",
    "so it is not as easy to modify the number of channels as in VGG.\n",
    "To have a reasonable training time on Fashion-MNIST,\n",
    "we reduce the input height and width from 224 to 96.\n",
    "This simplifies the computation.\n",
    "The changes in the shape of the output\n",
    "between the various modules is demonstrated below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "7"
    }
   },
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "float lr = 0.1f;\n",
    "Model model = Model.newInstance(\"cnn\");\n",
    "model.setBlock(block);\n",
    "\n",
    "Loss loss = Loss.softmaxCrossEntropyLoss();\n",
    "\n",
    "Tracker lrt = Tracker.fixed(lr);\n",
    "Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build();\n",
    "\n",
    "DefaultTrainingConfig config = new DefaultTrainingConfig(loss).optOptimizer(sgd) // Optimizer (loss function)\n",
    "        .optDevices(Device.getDevices(1)) // single GPU\n",
    "        .addEvaluator(new Accuracy()) // Model Accuracy\n",
    "        .addTrainingListeners(TrainingListener.Defaults.logging()); // Logging\n",
    "\n",
    "Trainer trainer = model.newTrainer(config);\n",
    "\n",
    "NDArray X = manager.randomUniform(0f, 1.0f, new Shape(1, 1, 96, 96));\n",
    "trainer.initialize(X.getShape());\n",
    "Shape currentShape = X.getShape();\n",
    "\n",
    "for (int i = 0; i < block.getChildren().size(); i++) {\n",
    "    Shape[] newShape = block.getChildren().get(i).getValue().getOutputShapes(new Shape[]{currentShape});\n",
    "    currentShape = newShape[0];\n",
    "    System.out.println(block.getChildren().get(i).getKey()+ i + \" layer output : \" + currentShape);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Acquisition and Training\n",
    "\n",
    "As before, we train our model using the Fashion-MNIST dataset.\n",
    " We transform it to $96 \\times 96$ pixel resolution\n",
    " before invoking the training procedure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 128;\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 10);\n",
    "\n",
    "double[] trainLoss;\n",
    "double[] testAccuracy;\n",
    "double[] epochCount;\n",
    "double[] trainAccuracy;\n",
    "\n",
    "epochCount = new double[numEpochs];\n",
    "\n",
    "for (int i = 0; i < epochCount.length; i++) {\n",
    "    epochCount[i] = (i + 1);\n",
    "}\n",
    "\n",
    "FashionMnist trainIter = FashionMnist.builder()\n",
    "        .addTransform(new Resize(96))\n",
    "        .addTransform(new ToTensor())\n",
    "        .optUsage(Dataset.Usage.TRAIN)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "FashionMnist testIter = FashionMnist.builder()\n",
    "        .addTransform(new Resize(96))\n",
    "        .addTransform(new ToTensor())\n",
    "        .optUsage(Dataset.Usage.TEST)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "trainIter.prepare();\n",
    "testIter.prepare();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "8"
    }
   },
   "outputs": [],
   "source": [
    "Map<String, double[]> evaluatorMetrics = new HashMap<>();\n",
    "double avgTrainTimePerEpoch = 0;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Training.trainingChapter6(trainIter, testIter, numEpochs, trainer, evaluatorMetrics, avgTrainTimePerEpoch);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainLoss = evaluatorMetrics.get(\"train_epoch_SoftmaxCrossEntropyLoss\");\n",
    "trainAccuracy = evaluatorMetrics.get(\"train_epoch_Accuracy\");\n",
    "testAccuracy = evaluatorMetrics.get(\"validate_epoch_Accuracy\");\n",
    "\n",
    "System.out.printf(\"loss %.3f,\", trainLoss[numEpochs - 1]);\n",
    "System.out.printf(\" train acc %.3f,\", trainAccuracy[numEpochs - 1]);\n",
    "System.out.printf(\" test acc %.3f\\n\", testAccuracy[numEpochs - 1]);\n",
    "System.out.printf(\"%.1f examples/sec\", trainIter.size() / (avgTrainTimePerEpoch / Math.pow(10, 9)));\n",
    "System.out.println();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Contour Gradient Descent.](https://d2l-java-resources.s3.amazonaws.com/img/chapter_convolution-modern-cnn-googleNet.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"train loss\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"test acc\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "    DoubleColumn.create(\"epoch\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "    DoubleColumn.create(\"metrics\", ArrayUtils.addAll(trainLoss, ArrayUtils.addAll(trainAccuracy, testAccuracy))),\n",
    "    StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epoch\", \"metrics\", \"lossLabel\"),\"text/html\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "* The Inception block is equivalent to a subnetwork with four paths. It extracts information in parallel through convolutional layers of different window shapes and maximum pooling layers. $1 \\times 1$ convolutions reduce channel dimensionality on a per-pixel level. Max-pooling reduces the resolution.\n",
    "* GoogLeNet connects multiple well-designed Inception blocks with other layers in series. The ratio of the number of channels assigned in the Inception block is obtained through a large number of experiments on the ImageNet dataset.\n",
    "* GoogLeNet, as well as its succeeding versions, was one of the most efficient models on ImageNet, providing similar test accuracy with lower computational complexity.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. There are several iterations of GoogLeNet. Try to implement and run them. Some of them include the following:\n",
    "    * Add a batch normalization layer :cite:`Ioffe.Szegedy.2015`, as described\n",
    "      later in :numref:`sec_batch_norm`.\n",
    "    * Make adjustments to the Inception block\n",
    "      :cite:`Szegedy.Vanhoucke.Ioffe.ea.2016`.\n",
    "    * Use \"label smoothing\" for model regularization\n",
    "      :cite:`Szegedy.Vanhoucke.Ioffe.ea.2016`.\n",
    "    * Include it in the residual connection\n",
    "      :cite:`Szegedy.Ioffe.Vanhoucke.ea.2017`, as described later in\n",
    "      :numref:`sec_resnet`.\n",
    "1. What is the minimum image size for GoogLeNet to work?\n",
    "1. Compare the model parameter sizes of AlexNet, VGG, and NiN with GoogLeNet. How do the latter two network architectures significantly reduce the model parameter size?\n",
    "1. Why do we need a large range convolution initially?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
